/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sample.discount;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.sadhar.sia.common.ClassConnection;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author hendro
 */
public class DiscountDAOImpl implements DiscountDAO {

    public DiscountDAOImpl(){
        ClassConnection.getTransactionProxyFactoryBean().setTarget(this);
    }

    public List<Discount> list() throws Exception {
        List<Discount> discounts = new ArrayList<Discount>();
        List<Map> row = ClassConnection.getJdbc().queryForList("SELECT * FROM dbproduct.discount");
        for(Map m : row){
            Discount disc = new Discount();
            disc.setId(Integer.valueOf(m.get("id").toString()));
            disc.setName(m.get("name").toString());
            discounts.add(disc);
        }
        return discounts;
    }

    public Discount select(int id) throws Exception {
        Discount disc  = null;
        String sql = "SELECT * FROM dbproduct.discount WHERE id=?";
        disc = (Discount) ClassConnection.getJdbc().queryForObject(sql, new Object[]{id},new RowMapper(){

            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Discount(
                        rs.getInt("id"),
                        rs.getString("name")
                        );
            }

        });
        return disc;
    }

}
